﻿
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Models.Common;
using Models.JsonResultModel;
using ServiceWeb.DBGateway;
using Models.WebAdmin;
using ServiceWeb.WebAdmin;
using UtilsBase;
using UtilsORM;
using UtilsORM.MySqlData;
using GatewayServer.Common;

namespace GatewayServer.Controllers
{
    public class DeviceController : BaseMagerController
    {
        EFYihongIotContext ef = new EFYihongIotContext();


        public IActionResult ListZTree(iot_product reqProduct)
        {
            ViewData["reqProduct"] = reqProduct;
            return View();
        }


        public IActionResult list(IFormCollection FC, HttpReqModel httpRequest, iot_device reqDevice, iot_product reqProduct, string m_guid, int PageIndex = 1, int PageSize = 15, string type = "1")
        {
            ViewData["reqDevice"] = reqDevice;
            ViewData["reqProduct"] = reqProduct;
            ViewBag.d_gw_d_guid = httpRequest.gwdguid;



            List<SugarParameter> sugarParameters = new List<SugarParameter>();
            int totalRecord = 0;
            string sqlwhere = "  and d_visible=0  and m_attribute!=3 ";
            if (!string.IsNullOrEmpty(httpRequest.name))
            {
                sqlwhere = sqlwhere + " and d_name like CONCAT('%',@name,'%') ";
                sugarParameters.Add(new SugarParameter("name", httpRequest.name));
            }

            if (!string.IsNullOrEmpty(httpRequest.gwdguid))
            {
                sqlwhere = sqlwhere + "  and d_gw_d_guid = @d_gw_d_guid ";
                sugarParameters.Add(new SugarParameter("d_gw_d_guid", httpRequest.gwdguid));
            }
            if (!string.IsNullOrEmpty(reqProduct.p_guid))
            {
                sqlwhere = sqlwhere + "  and d_p_guid = @d_p_guid ";
                sugarParameters.Add(new SugarParameter("d_p_guid", reqProduct.p_guid));
            }
            //else
            //{
            //    sqlwhere = sqlwhere + "    and d_is_template=0 ";
            //}

            if (!string.IsNullOrEmpty(FC["hid_pageIndex"]))
            {
                PageIndex = int.Parse(FC["hid_pageIndex"].ToString());

            }
            if (!string.IsNullOrWhiteSpace(reqDevice.d_group_guid))
            {
                sqlwhere = sqlwhere + " and d_group_guid=@d_group_guid";
                sugarParameters.Add(new SugarParameter("d_group_guid", reqDevice.d_group_guid));
            }
            if (!string.IsNullOrWhiteSpace(reqDevice.d_gw_d_guid))
            {
                sqlwhere = sqlwhere + " and d_gw_d_guid=@d_gw_d_guid";
                sugarParameters.Add(new SugarParameter("d_gw_d_guid", reqDevice.d_gw_d_guid));
            }
            if (!string.IsNullOrWhiteSpace(reqDevice.d_code))
            {
                sqlwhere = sqlwhere + " and d_code=@d_code";
                sugarParameters.Add(new SugarParameter("d_code", reqDevice.d_code));
            }


            if (!string.IsNullOrEmpty(httpRequest.status))
            {
                //设置状态
                sqlwhere = sqlwhere + " and d_status=@status";
                sugarParameters.Add(new SugarParameter("status", httpRequest.status));
            }

            if (!string.IsNullOrEmpty(m_guid))
            {
                ViewData["m_guid"] = m_guid;
                sqlwhere = sqlwhere + "  and d_model_guid = @m_guid ";
                sugarParameters.Add(new SugarParameter("m_guid", m_guid));
            }

            string sql = "select  a.* ,m.m_code,m.m_name machine_model,(select d_name from iot_device where d_guid=a.d_gw_d_guid) gwname,case when gw.gw_live_time  is not null  and gw.gw_live_time>date_add('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',interval -2 minute) then '在线' when gw.gw_live_time is not null then '离线' else '' end onlinestate  from iot_device a inner join iot_device_model m on m.m_guid=d_model_guid  left join iot_device_gateway gw on d_gw_d_guid=gw_d_guid where 1=1 " + sqlwhere;
            DataTable dt = MySqlYihongIot.getPageDataTable(PageIndex, PageSize, sql, sugarParameters, "d_id desc", ref totalRecord);


            ViewData["DataList"] = dt;

            ViewBag.PageSize = PageSize;
            ViewBag.RecordCount = totalRecord;//总条数
            ViewBag.PageCount = totalRecord % PageSize == 0 ? totalRecord / PageSize : totalRecord / PageSize + 1;//分的页数
            ViewBag.PageIndex = PageIndex;//当前页码

            return View(httpRequest);
        }
        public IActionResult edit(HttpReqModel httpReqModel, iot_product reqProduct)
        {
            ViewBag.d_p_guid = reqProduct.p_guid;
            ViewBag.gwdguid = httpReqModel.gwdguid;
            if (httpReqModel.order == "upd")
            {
                ViewBag.d_guid = httpReqModel.guid.ToString();
            }
            else
            {
                ViewBag.d_guid = Guid.NewGuid().ToString();
            }
            ViewBag.order = httpReqModel.order;

            return View();
        }

        public RespResultData saveAll(IFormCollection FC, HttpReqModel httpRequest, iot_device req)
        {

            new DBIotDevice().saveAll(LoginUserInfo, req);
            return RespResult.Sucess();
        }

        public RespResultData getDevice(HttpReqModel httpRequest)
        {
            return RespResult.Sucess(new DBIotDevice().getDevice(httpRequest.guid));
        }

        public RespResultData getModelList()
        {
            return RespResult.Sucess(new DBIotDeviceModel().getDeviceModelList().Where(c => c.m_attribute != 3).ToList());
        }
        public RespResultData getModel(HttpReqModel httpRequest)
        {
            return RespResult.Sucess(new DBIotDeviceModel().getDeviceModelList().Where(c => c.m_attribute != 3 && c.m_guid == httpRequest.guid).First());
        }


        public RespResultData getDeviceModel(HttpReqModel httpRequest, iot_product product)
        {
            List<iot_device_model> models = new DBIotDeviceModel().getDeviceModelList();

            return RespResult.Sucess(models);
        }
        public RespResultData getGateWayList(HttpReqModel httpRequest, iot_product product)
        {
            List<iot_device> devices = new DBIotDevice().getDeviceGateWayList();
            if (!string.IsNullOrEmpty(product.p_guid))
            {
                devices = devices.Where(c => c.d_p_guid == product.p_guid).ToList();
            }
            else
            {
                devices = devices.ToList();
            }


            if (!string.IsNullOrEmpty(httpRequest.gwdguid))
            {
                devices = devices.Where(c => c.d_guid == httpRequest.gwdguid).ToList();
            }
            return RespResult.Sucess(devices);
        }

        public RespResultData getGroupList()
        {
            return RespResult.Sucess(new DBIotDeviceGroup().getList(LoginUserInfo.userCompanyGuid));
        }

        public RespResultData changeStatus(HttpReqModel httpReqModel)
        {
            new DBIotDevice().changeStatus(httpReqModel.guid);
            return RespResult.Sucess();
        }


        public RespResultData del(HttpReqModel httpReqModel)
        {
            new DBIotDevice().del(httpReqModel.guid);
            return RespResult.Sucess();
        }
        [HttpPost]
        public string ListZTreeData(HttpReqModel requestModel, iot_product reqProduct)
        {

            ZtreeItemModel ZI = new ZtreeItemModel();
            List<ZtreeItemModel> ZIList = new List<ZtreeItemModel>();
            ZIList.AddRange(new ServiceGateWay().getZTreeGateWayList(reqProduct.p_guid));//加载下级
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            string result = JsonConvert.SerializeObject(ZIList, Formatting.Indented, settings);//需要注意的是，如果返回的是一个集合，那么还要在它的上面再封装一个类。否则客户端收到会出错的。
            return result;
        }
    }
}